#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   users.py
@Time    :   2021/02/06 12:26:37
@Author  :   superjin
@Version :   1.0
'''

from typing import Any
from datetime import timedelta
from fastapi.exceptions import ValidationException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm.session import Session
from common.deps import get_db
from exceptions import custom_exc
from core.response import response_code
from core.schemas.user import UserOutResponse
from datetime import datetime
from core.security import create_access_token
from core.schemas.user import UserCreate
from setting.web import settings
import crud

router = APIRouter()

@router.post("/login", summary="用户登陆")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """
    此接口用于用户注册
    登录后会返回JWT类型的TOKEN\n
    TOKEN中包含了用户USER ID,ROLE等信息
    """
    user = crud.user.authenticate(db, form_data.username, form_data.password)
    if user is None:
        return response_code.resp_502(message="用户名或密码错误")

    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        user.role, user.user_id, expires_delta=access_token_expires
    )
    return {"access_token": access_token,
            "token_type": "bearer",
            "expire_at": datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)}

@router.post("/register", summary="用户注册",response_model=UserOutResponse)
async def register_user(new_user:UserCreate,db: Session = Depends(get_db)):
    """
    此接口用于用户注册\n
    用户注册后默认赋予USER角色
    """
   # try:
    res_user = crud.user.create(db, new_user)
    return response_code.resp_200(data =res_user,message='成功')
